/**
 * 
 */
package com.cipe.cmrs.util;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Incepio
 *
 */
public class RequestUtil {

    /**
     * Convenience method to get the application's URL based on request
     * variables.
     */
    public static String getAppURL(HttpServletRequest request) {
        StringBuffer url = new StringBuffer();
        int port = request.getServerPort();
        if (port < 0) {
            port = 80; // Work around java.net.URL bug
        }
        String scheme = request.getScheme();
        url.append(scheme);
        url.append("://");
        url.append(request.getServerName());
        if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
            url.append(':');
            url.append(port);
        }
        url.append(request.getContextPath());
        return url.toString();
    }
	
    public static void setCacheExpireDate(HttpServletResponse response) {
		if (response != null) {
			Calendar cal = GregorianCalendar.getInstance();
			cal.add(Calendar.YEAR, 1);
			response.setHeader("Cache-Control", "public, max-age=" + cal.getTimeInMillis() + ", must-revalidate");
			response.setHeader("Expires", htmlExpiresDateFormat().format(cal.getTime()));
		}
	}

	private static DateFormat htmlExpiresDateFormat() {
		DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
		httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
		return httpDateFormat;
	}

	public static String getContextRelativeURL(ServletContext application, String source) {
		String path = application.getRealPath(source);

		File file = new File(path);
		
		StringBuffer stringBuffer = new StringBuffer();
//		stringBuffer.append(application.getContextPath());
		stringBuffer.append(source);
		stringBuffer.append("?_uniqueId=");
		stringBuffer.append(file.length());
		stringBuffer.append("-");
		stringBuffer.append(file.lastModified());
		return stringBuffer.toString();
	}
}
